import { jumpExternalMini } from '@/utils/utils.js'
export default {
	computed: {
	  environment() {
	    return this.$store.state.environment
	  },
	  ip() {
	    return this.$baseUrl;
	  },
	  // 顶部高度数据
	  commonHeight() {
	    return this.$store.state.commonHeight
	  },
	  userInfo() {
	    return this.$store.state.userInfo;
	  },
	  miniAppId() {
	    return this.$store.state.miniAppId;
	  },
	  tabListData() {
	    return uni.getStorageSync('tabListData');
	  },
	  tabBarHeight() {
	    return uni.getStorageSync('tabBarHeight');
	  }
	},
	methods: {
		// 打开服务
		async openService(status, item1) {
			let item = this.appAllList.filter(e => { return e.appId == item1.appId })[0]
			let appUrl = item.h5Url
			// 第三方  链接跳转
			if (appUrl.indexOf('wx://') > -1) {
				// 打开别人的小程序
				const res = jumpExternalMini(item.h5Url)
				if (res) {
					// 成功跳转
					return
				}
			}
			if (appUrl.indexOf('#小程序://') > -1) {
				// 打开别人的小程序地址  #小程序://喜茶GO/xPuMLweMhJBK28v
				wx.navigateToMiniProgram({
					shortLink: appUrl,
					envVersion: 'release',
					success(res) {
						// 打开成功
					}
				})
				return
			}
			// 判断是否可以继续往下
			let { t, appCodeNew, noToken } = await this.__appCode(item)
			if (!t && !noToken) {
				this.showPopup = true;
				return
			}
			if (!t && noToken) {
				uni.navigateTo({
        	url: `${this.$loginPath}?isBack=1`
				})
				return
			}

			if (!item.refDevopsAppId && item.touristAllow !== 1) {
				  // 是否为游客
				let projectInfo = this.newProjectInfo ? Object.keys(this.newProjectInfo).length ? this.newProjectInfo : this.projectInfo : this.projectInfo
				  const isVisitor = !!projectInfo.userApproveId ? '0' : '1' // 0为认证用户,1为非认证用户
				  if (isVisitor === '1') {
					  // 自定义应用 不允许游客
					  this.showPopup = true;
					  return
				  }
			}

			if (['395', '396'].includes((item.appCode))) {
				// 门禁门锁、智能家居
				uni.showToast({
					icon: 'none',
					title: '敬请期待',
					duration: 2000
				});
				return
			}
			// 是否为游客
			let token = uni.getStorageSync('accessToken')
			let { projectId, projectName, tenantId } = this.projectInfo
			let projectInfo = this.newProjectInfo ? Object.keys(this.newProjectInfo).length ? this.newProjectInfo : this.projectInfo : this.projectInfo
			let isVisitor = !!projectInfo.userApproveId ? '0' : '1' // 0为认证用户,1为非认证用户
			let appName = item.alias || item.appName;
			// if (!(this.hasPhone())) return
			// 下面几个不要认证就能跳转
			if (['340', '338', '336', '337', '304', '335', '339', '342', '352', '353', '369', '372', '388', '389', '302', '393', '398', '417'].includes(appCodeNew)) {
				let appUrl = item.h5Url
				let url = ''
				if (item.appCode === '304') {
					const isValid = this.validShopSetting()
					if (!isValid) {
						return
					}
					// 商城
					const shopUrl = uni.getStorageSync('shopUrl')
					const projectAuth = !!this.projectInfo.userApproveId ? '1' : '0'
					url = `${shopUrl}/h5/?openType=outh5&t=${Date.now()}#/pages/empty/empty?projectId=${this.projectInfo.projectId}&orgId=${this.projectInfo.tenantId}&openId=${this.openId}&projectAuth=${projectAuth}&phone=${this.userInfo.mobile}`
				} else if (item.appCode === '385') {
					const isValid = this.validShopSetting()
					if (!isValid) {
						return
					}
					// 商城
					const shopUrl = uni.getStorageSync('shopUrl')
					const projectAuth = !!this.projectInfo.userApproveId ? '1' : '0'
					url = `${shopUrl}/store/?openType=outh5&t=${Date.now()}#/pages/empty/empty?projectId=${this.projectInfo.projectId}&orgId=${this.projectInfo.tenantId}&openId=${this.openId}&projectAuth=${projectAuth}&phone=${this.userInfo.mobile}`
				}
				else if (['338', '352', '353', '393'].includes(item.appCode)) {
					// 房屋租赁\房产销售\租售服务\我要租房
					url = `${appUrl}?token=${token}&projectName=${projectName}&projectId=${projectId}&tenantId=${tenantId}&openId=${this.openId}&title=${item.alias || item.appName}`
				}
				else if (item.appCode === '340') {
					// 企业介绍
					url = `${appUrl}?token=${token}&projectName=${projectName}&projectId=${projectId}&orgId=${tenantId}&openId=${this.openId}&title=${item.alias || item.appName}`
				} else if (item.appCode === '336') {
					// 新闻
					url = `${appUrl}?token=${token}&projectName=${projectName}&projectId=${projectId}&orgId=${tenantId}&openId=${this.openId}&title=${item.alias || item.appName}&clientType=miniProgram`
				} else if (item.appCode === '337') {
					// 政策
					url = `${appUrl}?token=${token}&projectName=${projectName}&projectId=${projectId}&orgId=${tenantId}&openId=${this.openId}&title=${item.alias || item.appName}`
				} else if (item.appCode === '335') {
					// 便民服务
					let url = `/pages/home/convenientServerAll/convenientServerAll?tenantId=${tenantId}&projectId=${projectId}&title=${item.alias || item.appName}`
					uni.navigateTo({
						url
					})
					return
					// 领劵中心
				} else if (item.appCode === '369') {
					let url = `/coupon/pages/certionCenter/index?tenantId=${tenantId}&projectId=${projectId}&title=${item.alias || item.appName}`
					uni.navigateTo({
						url
					})
					return
					// 商家核销
				}
				else if (item.appCode === '339') {
					// 社区简介
					let url = `/pages/communityDetails/index?projectId=${projectId}&title=${item.alias || item.appName}`
					uni.navigateTo({
						url
					})
				} else if (item.appCode === '342') {
					// 社区活动
					url = `${appUrl}?token=${token}&projectName=${projectName}&projectId=${projectId}&orgId=${tenantId}&openId=${this.openId}&title=${item.alias || item.appName}&clientType=miniProgram`
				} else if (item.appCode === '417') {
					// 食堂消费码
					let str = `token=${token}&projectName=${projectName}&projectId=${projectId}&orgId=${tenantId}&openId=${this.openId}&mobile=${this.userInfo.mobile}`
					url = `${appUrl}?${str}`
				}
				else if (item.appCode === '372') {
					// 物品租赁
					let str = `token=${token}&projectName=${projectName}&projectId=${projectId}&orgId=${tenantId}&openId=${this.openId}`
					url = `${appUrl}?${str}`
				} else if (item.appCode === '388') {
					// 服务产品
					// let url = `${this.urls}/thirdParty?tenantId=${tenantId}&userPhoneNumber=${this.userInfo.mobile}&serviceTypeId=${item.serviceTypeId}&projectId=${projectInfo.projectId}&userName=${this.userInfo.nickname}&title=${title}&token=${token}`
					let str = `token=${token}&projectName=${projectName}&projectId=${projectId}&tenantId=${tenantId}&userPhoneNumber=${this.userInfo.mobile}&userName=${this.userInfo.nickname}&title=${item.alias || item.appName}&type=1`
					url = `${appUrl}?${str}`
				} else if (item.appCode === '389') {
					// 服务商库
					let str = `token=${token}&projectName=${projectName}&projectId=${projectId}&tenantId=${tenantId}&userPhoneNumber=${this.userInfo.mobile}&userName=${this.userInfo.nickname}&title=${item.alias || item.appName}&type=2`
					url = `${appUrl}?${str}`
				}
				else if (item.appCode === '302') {
					// 场地处理 queryGeneralSettingData： 场地初始化配置数据为0 需认证
					if (!this.projectInfo.userApproveId && this.queryGeneralSettingData.settingValue === '0') {
						uni.hideTabBar();
						this.showPopup = true;
						return;
					}
					// 场地预约
					url = `${appUrl}?token=${token}&openId=${this.openId}&tenantId=${tenantId}&projectId=${projectId}`
				} else if (item.appCode === '398') {
					// 图文列表
					url = `${appUrl}?token=${token}&projectId=${projectId}&title=${item.alias || item.appName}`
				}
				this.$Router.push({
					name: 'webViewPage',
					params: {
						url
					}
				});
				return
			}
			if (item.appCode === '324') {
				uni.navigateTo({
					url: '/pages/openDoor/index'
				})
				return
			}
			if (item.appCode === '425') {
				uni.navigateTo({
					url: `/pages/rentingHome/index?isShowHeader=1&appName=${appName}`
				})
				return
			}
			if (item.appCode === '433') {
				uni.navigateTo({
					url: `/pages/identityAuthentication/index`
				})
				return
			}
			if (item.appId !== '100857') {
				// 如果是顶部的数据，则appInfoName有值，如果是全部的服务数据，取otherName或者appName
				if (!this.projectInfo.userApproveId && item.appCode !== '310' && item.appName !== '场地预约' && item.appName !== '商城' && item.appName !== '我要租房' && item.refDevopsAppId) {
					uni.hideTabBar();
					this.showPopup = true;
					return;
				}
				if (['950001', '950002'].includes(item.id)) {
					this.$refs.uToast.show({
						message: '正在开发中，敬请期待'
					});
					return;
				}
				if ([2, 3].indexOf(item.appStatus) > -1) {
					this.$refs.uToast.show({
						message: '正在开发中，敬请期待'
					});
					return;
				}
				if (!this.openId) { // 投诉建议需要openId，当不存在openId时，跳转到登录页去
					if (!['物业缴费', '快速报事', '投诉建议', '开票中心', '预交充值', '访客邀请', '访客登记', '商城', '公区报修', '场地预约', '生活缴费'].includes(appName)) {
						this.$refs.uToast.show({
							message: '暂未开通此服务'
						});
						return;
					}
				}
				let url = '';
				if (appUrl.indexOf('roc-finance-owner-h5') > -1) {
					if (!this.openId) { // 查缴费需要openId，当不存在openId时，跳转到登录页去
						this.noOpenIdFlag = true
						return
					}
					// #ifdef MP-WEIXIN
					await this.setMiniNotice('2')
					// #endif
					url =
						`${appUrl}?projectId=${projectId}&projectName=${projectName}
						&userPhoneNumber=${this.userInfo.mobile}&openId=${this.openId}&headImgUrl=${this.userInfo.photo}
						&miniAppId=${this.miniAppId}&logined=true&accessToken=${uni.getStorageSync('accessToken')}&showBack=1`;
				} else if (appUrl.indexOf('roc-electronic-invoicing-h5') > -1) { // 开票中心
					// #ifdef MP-WEIXIN
					await this.setMiniNotice('2')
					// #endif
					url =
						`${appUrl}?projectId=${projectId}&projectName=${projectName}
						&userPhoneNumber=${this.userInfo.mobile}&openId=${this.openId}&headImgUrl=${this.userInfo.photo}
						&miniAppId=${this.miniAppId}&logined=true&accessToken=${uni.getStorageSync('accessToken')}`;
				} else if (appUrl.indexOf('roc-customer-service-owner-h5') > -1) {
					const pos = appUrl.indexOf('/roc-customer-service-owner-h5')
					if (pos != 0) {
						appUrl = appUrl.substring(pos)
					}
					if (item.appCode === '310') {
						// 公区报修
						url =
							`${appUrl}?token=${uni.getStorageSync('accessToken')}&mobile=${this.userInfo.mobile}&isVisitor=${isVisitor}&projectId=${projectId}&projectName=${projectName}&openId=${this.openId}&tenantId=${tenantId}&userId=${this.userInfo.userManagerId}&userName=${this.userInfo.nickname}&headImgUrl=${encodeURIComponent(this.userInfo.photo)}&logined=true&isMini=1`;
					}
					else if (appUrl.includes('quicklyThings')) {
						if (!this.openId) { // 预交充值需要openId，当不存在openId时，跳转到登录页去
							this.noOpenIdFlag = true
							return
						}
						// 区分开 快速报事和投诉建议
						let fromType = '1' // 默认快速报事
						let types = []
						if (item.appCode === '224') {
							fromType = '2'
							types = await this.getServiceTypes('YZD_TSJY')
						} else if (item.appCode === '225') {
							types = await this.getServiceTypes()
						}
						if (['224', '225'].includes(item.appCode)) {
							if (!types.length) {
								this.$refs.uToast.show({ message: '该功能未开通' })
								return
							}
						}
						const arr = appUrl.trim().split('#/')
						if (arr.length > 0 && arr[1].includes('?')) {
							url =
								`${appUrl.trim()}&mobile=${this.userInfo.mobile}&openId=${this.openId}&isVisitor=${isVisitor}&projectId=${projectId}&projectName=${projectName}&fromType=${fromType}&tenantId=${tenantId}&headImgUrl=${this.userInfo.photo}&logined=true&isMini=1`;
							if (!item.refDevopsAppId) {
								  // 自定义应用
								  url += `&appName=${item.appName}`
							}
						} else {
							url =
								`${appUrl.trim()}?mobile=${this.userInfo.mobile}&openId=${this.openId}&isVisitor=${isVisitor}&projectId=${projectId}&projectName=${projectName}&fromType=${fromType}&tenantId=${tenantId}&headImgUrl=${this.userInfo.photo}&logined=true&isMini=1`;
						}
					} else if (appUrl.includes('publicThings')) {
						if (!this.openId) { // 预交充值需要openId，当不存在openId时，跳转到登录页去
							this.noOpenIdFlag = true
							return
						}
						// 公区报事
						let resData = await this.getServiceTypes()
						let find = resData.find(x => x.serviceTypeCode === 'ST_GQBX')

						if (!find) {
							this.$refs.uToast.show({
								message: '该功能未开通'
							});
							return
						}
						url =
							`${appUrl.trim()}?mobile=${this.userInfo.mobile}&projectId=${projectId}&projectName=${projectName}&openId=${this.openId}&tenantId=${tenantId}&logined=true&isMini=1&isVisitor=${isVisitor}&userId=${this.userInfo.userManagerId}&userName=${this.userInfo.nickname}&headImgUrl=${encodeURIComponent(this.userInfo.photo)}`;
					}

				} else if (appUrl.indexOf('roc-prepay-h5') > -1) { // 预交充值
					if (!this.openId) { // 预交充值需要openId，当不存在openId时，跳转到登录页去
						this.noOpenIdFlag = true
						return
					}
					url =
						`${appUrl}?phone=${this.userInfo.mobile}&projectId=${projectId}&openId=${this.openId}&miniAppId=${this.miniAppId}&accessToken=${uni.getStorageSync('accessToken')}`;
				}else if (item.appCode === '285') {
					// 问卷调查
					url = `${appUrl}?token=${token}&houseId=${this.projectInfo.houseId}&houseCode=${this.projectInfo.houseCode}&houseName=${this.projectInfo.houseName}&projectName=${projectName}&projectId=${projectId}&tenantId=${tenantId}&userId=${this.userInfo.userManagerId}&userName=${this.userInfo.nickname}&memberId=${this.userInfo.memberId}&isVisitor=${isVisitor}`
					} else if (appUrl.indexOf('roc-notice-owner-h5') > -1 &&
					(appUrl.indexOf('visitRegister') > -1 || appUrl.indexOf('news') > -1 || appUrl.indexOf('information') > -1
						|| appUrl.indexOf('activityList') > -1 || appUrl.indexOf('enterprise') > -1 || appUrl.indexOf('visitInvite') > -1
						|| appUrl.indexOf('quesetion') > -1 || appUrl.indexOf('orderList') > -1 || appUrl.indexOf('familyVideo') > -1 || appUrl.indexOf('audit') > -1
						|| appUrl.indexOf('decorationApply') > -1) || appUrl.indexOf('imageListDetial') > -1 || appUrl.indexOf('goodsRelease') > -1) {
					if (item.appName === '场地预约') {
						// 场地处理 queryGeneralSettingData： 场地初始化配置数据为0 需认证
						if (!this.projectInfo.userApproveId && this.queryGeneralSettingData.settingValue === '0') {
							uni.hideTabBar();
							this.showPopup = true;
							return;
						}
						url = `${appUrl}?token=${token}&projectName=${projectName}
						&projectId=${projectId}&tenantId=${tenantId}&openId=${this.openId}&clientType=miniProgram`
					} else if (item.appCode === '330') {
						// 家园视频
						let url = `/coupon/pages/videoLive/index?projectId=${projectId}&phone=${this.userInfo.mobile}&title=${appName}`
						uni.navigateTo({
							url
						})
					} else if (item.appCode === '233') {
						// 装修申请
						url = `${appUrl}?token=${token}&projectId=${projectId}&projectName=${projectName}&orgId=${tenantId}&isMini=true`
					} else if (item.appCode === '232') {
						//访客邀请
						url = `${appUrl}?token=${token}&projectId=${projectId}&projectName=${projectName}&orgId=${tenantId}&isMini=true&clientType=miniProgram`
					} else if (item.appCode === '386') {
						//访客审核
						url = `${appUrl}?token=${token}&projectId=${projectId}&projectName=${projectName}&orgId=${tenantId}&isMini=true`
					} else if (item.appCode === '406') {
						// 物品放行
						url = `${appUrl}?token=${token}&projectName=${projectName}&projectId=${projectId}&orgId=${tenantId}&openId=${this.openId}&mobile=${this.userInfo.mobile}`
					}  else {
						url = appUrl + '?';
						if (this.projectInfo) {
							if (projectId) {
								url += 'projectId=' + projectId + '&projectName=' + projectName + '&isMini=true&' + 'orgId=' + tenantId + '&';
							}
						}
						url += `token=${token}`
					}
				} else if (item.appCode === '365') {
					// 论坛
					const projectAuth = !!this.projectInfo.userApproveId ? '1' : '0'
					url = `${appUrl}?token=${token}&projectId=${projectId}&orgId=${tenantId}&openId=${this.openId}&projectAuth=${projectAuth}&phone=${this.userInfo.mobile}&color=${this.colorConfig}`
				} else if (appUrl.indexOf('roc-rent-owner-h5') > -1) {
					// 租赁
					url = `${appUrl}?token=${token}&projectName=${projectName}
						&projectId=${projectId}&tenantId=${tenantId}&openId=${this.openId}`
				} else {
					const pos = appUrl.indexOf('?')
					if (pos === -1) {
						this.$refs.uToast.show({
							message: 'url地址需要有openType等参数'
						});
						return
					}
					let queryObj = {}
					let queryStr = appUrl.substring(pos + 1).replace(/#\/.*/, '')
					let queryArr = queryStr.split('&')

					queryArr.forEach((item) => {
						let arr = item.split('=')
						queryObj[arr[0]] = arr[1] || ''
					})

					let openType = queryObj['openType'] || 'outmini'
					if (openType === 'outmini') { // 如果是打开微信小程序
						let appId = queryObj['miniAppId']
						let path = qppUrl.substring(0, pos)
						wx.navigateToMiniProgram({
							appId, // 需要跳转到指定的小程序appid
							path, // 打开的页面
							envVersion: 'release',
							success(res) {
								// console.log(`成功打开小程序${path}`)
							}
						})
					} else if (openType === 'outh5') { // 打开外部h5
						let url = appUrl + '?'
						if (this.projectInfo) {
							if (this.projectInfo.projectId) {
								url += 'projectId=' + this.projectInfo.projectId + '&';
							}
							if (this.projectInfo.tenantId) {
								url += 'orgId=' + this.projectInfo.tenantId + '&';
							}
						}
						if (this.openId) {
							// projectAuth 已经认证的传1，否则传0(todo)
							const projectAuth = !!this.projectInfo.userApproveId ? '1' : '0'
							url += 'openId=' + this.openId + '&projectAuth=' + projectAuth + '&phone=' + this.userInfo.mobile;
						}
						// todo有这种场景时再开发
						this.$Router.push({
							name: 'webViewPage',
							params: {
								url
							}
						});
					} else if (openType === 'innerh5') { // 打开内部h5
						// todo有这种场景时再开发
					}
					return;
				}
				this.$Router.push({
					name: 'webViewPage',
					params: {
						url
					}
				});
			}
		},
	}
}
